package ferp.center.server.entity;

import com.google.appengine.api.datastore.Key;
import ferp.core.util.Convert;

import javax.persistence.*;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;

@NamedQueries({
    @NamedQuery(name = Profile.QUERY_GET_INACTIVE,
                query = "SELECT p FROM Profile p WHERE p.accessed < ?1"),

    @NamedQuery(name = Profile.QUERY_GET_ALL,
        query = "SELECT p FROM Profile p")

})

@Entity
public class Profile
{
  // delete inactive profiles
  public static final String QUERY_GET_INACTIVE = "deleteInactive";
  // delete inactive profiles
  public static final String QUERY_GET_ALL = "getAllProfiles";

  public Key getKey() {return key;}
  public void setDevice(Device device) {this.device = device.getKey();}
  public String getName() {return name;}
  public String getLocale() {return locale;}
  public int getLastPlayedPoolSize() {return lastPlayedPoolSize;}
  public void setName(String name) {this.name = name;}
  public void setLocale(String locale) {this.locale = locale;}
  //public void setPoolBalance(int balance) {this.poolBalance = balance;}
  public void setLastPlayedPoolSize(int pool) {this.lastPlayedPoolSize = pool;}
  public Date getCreated() {return created;}
  public void setCreated(Date created) {this.created = created;}
  public Date getAccessed() {return accessed;}
  public void setAccessed(Date accessed) {this.accessed = accessed;}
  public Collection<Rating> getRatings() {return ratings;}
  public void setRatings(Collection<Rating> ratings) {this.ratings = ratings;}

  public Device getDevice(EntityManager em)
  {
    if (device == null)
      return null;

    return em.find(Device.class, device);
  }

  public Rating getRating(String configuration)
  {
    for (Rating r : getRatings())
      if (Convert.configuration(r.getConfiguration()).equals(configuration))
        return r;

    return null;
  }

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Key key;
  // parent device key (unowned reference)
  private Key device;
  // player name
  private String name;
  // player locale ("en", "ru", etc.)
  private String locale;
  // player pool balance
  private int poolBalance;
  // last played game's pool size
  private int lastPlayedPoolSize;
  // profile creation date
  @Temporal(TemporalType.DATE)
  private Date created;
  // last access date
  @Temporal(TemporalType.DATE)
  private Date accessed;
  // list of associated ratings for different game configurations (one per config)
  @OneToMany(mappedBy = "profile", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private Collection<Rating> ratings = new LinkedList<Rating>();

  @Version
  private int version;
}
